#include <stdio.h>
#include "Thread_Pool.h"
#include "stdlib.h"

/**
 * @func: insert a task into threadpool's tasks
*/
void ThreadPool_InsertTask(Thread_Poolp poolp, void *(*func)(void*), void *arg)
{
    pthread_mutex_lock(&poolp->pool_mutex);
    
    //if the queue is full, block(生产者模型（资源仓库容量有限的情况，需要等待消费者把东西拿走)
    //if(poolp->q_rear+1 >= poolp->max_task)
    if(poolp->task_num >= poolp->max_task && (!poolp->shutdown))
    {
        pthread_cond_wait(&poolp->pool_cond_notfull, &poolp->pool_mutex);
    }    

    //insert into the queue
    if(poolp->tasks[poolp->q_rear].arg != NULL) //清空可能存在的队列中的 arg 参数
    {
       free(poolp->tasks[poolp->q_rear].arg);
       poolp->tasks[poolp->q_rear].arg == NULL;
    }
    poolp->tasks[poolp->q_rear].func = func;
    poolp->tasks[poolp->q_rear].arg = arg;
    poolp->q_rear = (poolp->q_rear+1)%(poolp->max_task);//环形队列
    
    poolp->task_num++;

    pthread_mutex_unlock(&poolp->pool_mutex); 
    
    //if there are idle worker, wake it up(生产者模型，当生产出产品后，通知消费者)
    //if there is no idle worker, nonsense, alse signal
    pthread_cond_signal(&poolp->pool_cond_notemp);
    printf("signal: notemp\n ");
}